package com.sunday.electric.service;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.text.TextUtils;

import com.sunday.common.logger.Logger;
import com.sunday.common.utils.NetworkUtils;
import com.sunday.electric.smack.SmackImpl;
import com.sunday.electric.ui.mine.OnLineHelpActivity;

import org.jivesoftware.smack.SmackException;
import org.jivesoftware.smack.StanzaListener;
import org.jivesoftware.smack.chat.ChatManager;
import org.jivesoftware.smack.filter.AndFilter;
import org.jivesoftware.smack.filter.StanzaFilter;
import org.jivesoftware.smack.filter.StanzaTypeFilter;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Stanza;

/**
 * Created by Administrator on 2016/2/16.
 */
public class ChatService extends Service {
    private static final String TAG = "ChatService";
    public static final int CONNECTED = 0;
    public static final int DISCONNECTED = -1;
    public static final int CONNECTING = 1;
    private IConnectionStatusCallback mConnectionStatusCallback;
    private boolean mIsFirstLoginAction;
    private Thread mConnectingThread;
    private SmackImpl mSmackable;

    private IBinder mBinder = new ChatBinder();
    private LoginStatusCallback loginStatusCallback;
    private onMessageCallback onMessageCallback;

    private ChatManager chatmanager;
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        String action = intent.getAction();
        if (!TextUtils.isEmpty(action)
                && TextUtils.equals(action, OnLineHelpActivity.LOGIN_ACTION)) {
            mIsFirstLoginAction = true;
        } else {
            mIsFirstLoginAction = false;
        }
        return mBinder;
    }

    public void setLoginStatusCallback(LoginStatusCallback loginStatusCallback) {
        this.loginStatusCallback = loginStatusCallback;
    }

    public void setOnMessageCallback(ChatService.onMessageCallback onMessageCallback) {
        this.onMessageCallback = onMessageCallback;
    }

    /**
     * 注册注解面和聊天界面时连接状态变化回调
     *
     * @param cb
     */
    public void registerConnectionStatusCallback(IConnectionStatusCallback cb) {
        mConnectionStatusCallback = cb;
    }

    public void unRegisterConnectionStatusCallback() {
        mConnectionStatusCallback = null;
    }

    public interface IConnectionStatusCallback {
        public void connectionStatusChanged(int connectedState, String reason);
    }

    public interface LoginStatusCallback{
        void  loginSuccess();
        void  loginFail();
    }


    public interface onMessageCallback{
        void processMsg(Message msg);
    }


    public class ChatBinder extends Binder {
        public ChatService getService() {
            return ChatService.this;
        }
    }

    // 登录
    public void Login() {
        if (!NetworkUtils.isConnectInternet(this)) {
         //   connectionFailed(NETWORK_ERROR);
            return;
        }
        if (mConnectingThread != null) {
            Logger.i("a connection is still goign on!");
            return;
        }
        mConnectingThread = new Thread() {
            @Override
            public void run() {
                try {
                    mSmackable = SmackImpl.getIns();
                    if (mSmackable.login()) {
                        // 登陆成功
                        //postConnectionScuessed();
                        addMessageListener();
                        loginStatusCallback.loginSuccess();
                        Logger.d(TAG,"登录成功");
                    } else {
                        // 登陆失败
                      //  postConnectionFailed(LOGIN_FAILED);
                        loginStatusCallback.loginFail();
                        Logger.d(TAG,"登录失败");
                    }
                } catch (Exception e) {
                    String message = e.getLocalizedMessage();
                    e.printStackTrace();
                } finally {
                    if (mConnectingThread != null)
                        synchronized (mConnectingThread) {
                            mConnectingThread = null;
                        }
                }
            }

        };
        mConnectingThread.start();
    }

    public ChatManager getChatmanager() {
        return ChatManager.getInstanceFor(mSmackable.getXMPPConnection());
    }

    private void addMessageListener(){
        StanzaFilter filter = new AndFilter(new StanzaTypeFilter(Message.class));
        StanzaListener myListener = new StanzaListener() {
            @Override
            public void processPacket(Stanza packet) throws SmackException.NotConnectedException {
                Logger.d(TAG,packet.getTo());
                Message message = (Message)packet;
                if(message.getType() == Message.Type.chat) {
                    if(message.getTo().equals("sunday@iz23gyb2iiyz/Smack")&&onMessageCallback!=null&&
                            !TextUtils.isEmpty(message.getBody())){
                        onMessageCallback.processMsg(message);
                    }
                    //single chat message
                } else if(message.getType() == Message.Type.groupchat) {

                    //group chat message
                } else if(message.getType() == Message.Type.error) {
                    //error message
                }

            }
        };
        SmackImpl.getIns().getXMPPConnection().addSyncStanzaListener(myListener, filter);
    }


}
